package indi.jp.project.business.yunying.service.impl;

import indi.jp.project.business.yunying.dao.FapiaoFiledDAO;
import indi.jp.project.core.entity.Datagrid;
import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.core.entity.po.AttachmentPO;
import indi.jp.project.core.service.AttachmentService;
import indi.jp.project.core.util.SerialUtil;
import indi.jp.project.process.service.FlowTaskService;
import indi.jp.project.business.yunying.entity.FapiaoFiled;
import indi.jp.project.business.yunying.service.FapiaoFiledService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.*;

@Service
public class FapiaoFiledServiceImpl implements FapiaoFiledService {

    @Resource
    private FapiaoFiledDAO fapiaoFiledDAO;

    @Resource
    private SerialUtil serialUtil;

    @Resource
    private FlowTaskService flowTaskService;

    @Resource
    private AttachmentService attachmentService;

    @Override
    public JsonResult queryGrid(FapiaoFiled fapiaoFiled) throws SQLException {
        List<FapiaoFiled> list = fapiaoFiledDAO.queryList(fapiaoFiled);
        int count = fapiaoFiledDAO.queryCount(fapiaoFiled);
        Datagrid<FapiaoFiled> datagrid = new Datagrid<>(list, count);
        return JsonResult.success(datagrid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult save(FapiaoFiled fapiaoFiled) throws Exception {
        String id;
        if (StringUtils.isBlank(fapiaoFiled.getId())) {
            id = String.valueOf(serialUtil.nextId());
            fapiaoFiled.setId(id);
            fapiaoFiledDAO.insert(fapiaoFiled);
        } else {
            id = fapiaoFiled.getId();
            fapiaoFiledDAO.update(fapiaoFiled);
        }
        List<AttachmentPO> attachments = fapiaoFiled.getAttachments();
        if (attachments != null && attachments.size() > 0) {
            attachmentService.delete(id);
            attachmentService.save(attachments, id);
        }
        flowTaskService.saveTaskFlow(id, fapiaoFiled.getFlowList());
        return JsonResult.success("保存成功");
    }

    @Override
    public JsonResult findById(String id) throws Exception {
        FapiaoFiled fapiaoFiled = fapiaoFiledDAO.findById(id);
        List<AttachmentPO> attachments = attachmentService.queryAttachments(id, null);
        fapiaoFiled.setAttachments(attachments);
        return JsonResult.success(fapiaoFiled);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult deleteById(String id) throws Exception {
        fapiaoFiledDAO.deleteById(id);
        flowTaskService.deleteFlowByTaskId(id);
        attachmentService.delete(id);
        return JsonResult.success();
    }

}
